package infra.mongodb.document.serializer;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;
import domain.model.project.ProjectSCM;
import domain.model.project.ProjectType;
import domain.model.project.support.ProjectBuilder;
import infra.mongodb.document.MongoDBProjectDocumentImpl;
import util.jackson.serializer.JacksonReader;

import java.io.IOException;

/**
 * @author Gregory Boissinot
 */
public class MongoDBProjectDocumentDeserializer extends JsonDeserializer<MongoDBProjectDocumentImpl> {

    private final JacksonReader jacksonReader;

    public MongoDBProjectDocumentDeserializer() {
        this.jacksonReader = new JacksonReader();
    }

    @Override
    public MongoDBProjectDocumentImpl deserialize(JsonParser jsonParser,
                                                  DeserializationContext ctxt) throws IOException {

        //-- Required elements
        JsonNode rootNode = jsonParser.getCodec().readTree(jsonParser);
        String version = jacksonReader.readRequiredFieldValue(rootNode, "version", String.class);
        String org = jacksonReader.readRequiredFieldValue(rootNode, "org", String.class);
        String name = jacksonReader.readRequiredFieldValue(rootNode, "name", String.class);
        String status = jacksonReader.readRequiredFieldValue(rootNode, "status", String.class);

        //-- Optional elements
        String description = jacksonReader.readOptionalField(rootNode, "description", String.class);
        String templateLocalFilePath = jacksonReader.readOptionalField(rootNode, "templateLocalFilePath", String.class);
        ProjectSCM projectSCM = jacksonReader.readOptionalField(rootNode, "scm", ProjectSCM.class);
        String type = jacksonReader.readOptionalField(rootNode, "type", String.class);
        ProjectType projectType = jacksonReader.readOptionalField(rootNode, type, ProjectType.class);

        ProjectBuilder projectBuilder = new ProjectBuilder(org, name, status);
        projectBuilder.projectSCM(projectSCM)
                .projectType(projectType)
                .description(description)
                .templateLocalFilePath(templateLocalFilePath);


        return new MongoDBProjectDocumentImpl(version, projectBuilder.build());
    }


}
